import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
import { GLOBAL_AUTH_TOKEN_KEY } from './constants';
import proxy from '../configs/host';
import { MessagePlugin } from 'tdesign-react';
import { NotificationPlugin } from 'tdesign-react';

const env = import.meta.env.MODE || 'development';
const API_HOST = proxy[env].API;

const SUCCESS_CODE = 200;
const TIMEOUT = 10 * 60 * 1000; // 10 minutes

interface ApiResponse<T> {
  code: number;
  data: T;
  message: string;
}

export const instance = axios.create({
  baseURL: '/api/v1/jupiter/blog',
  timeout: TIMEOUT,
  withCredentials: true,
});

// 将本地 token 注入到请求头，统一使用自定义 header: authorization-token
instance.interceptors.request.use((config) => {
  try {
    const token = localStorage.getItem(GLOBAL_AUTH_TOKEN_KEY);
    if (token) {
      config.headers = config.headers || {};
      (config.headers as any)['authorization-token'] = token;
    }
  } catch (e) {
    // ignore
  }
  return config;
});

instance.interceptors.response.use(
  // eslint-disable-next-line consistent-return
  (response) => {
    if (response.status === 200) {
      const { data } = response;
      if (data.code === SUCCESS_CODE) {
        return response;
      }
      return Promise.reject(data);
    }
    return Promise.reject(response?.data);
  },
  (error) => {
    // HTTP 错误状态（500、404 等）
    if (error.response) {
      const { status, data } = error.response;
      // 可以统一处理
      const msg = data?.message || `服务器错误（${status}）`;
      NotificationPlugin.error({
        title: '请求异常',
        content: msg,
        placement: 'top-right',
        duration: 3000,
        closeBtn: true,
      });
      return Promise.reject({ status, data });
    }
    // 网络错误或请求被阻断
    return Promise.reject(error);
  },
);

/**
 * 通用请求函数，自动类型推断和 data 拆包
 * @param url 请求地址
 * @param config axios 请求配置
 * @returns 返回类型自动是 ApiResponse<T> 中的 T
 */
const request = {
  async get<T = any>(url: string, config?: AxiosRequestConfig): Promise<ApiResponse<T>> {
    const res = await instance.get<ApiResponse<T>>(url, config);
    return res.data;
  },
  async post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<ApiResponse<T>> {
    const res = await instance.post<ApiResponse<T>>(url, data, config);
    return res.data;
  },

  async put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<ApiResponse<T>> {
    const res = await instance.put<ApiResponse<T>>(url, data, config);
    return res.data;
  },

  async delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<ApiResponse<T>> {
    const res = await instance.delete<ApiResponse<T>>(url, config);
    return res.data;
  },
};

export default request;
